package logic

import (
	"context"
	"fmt"
	"zhihu/models/cache"
	"zhihu/models/mysql"
	"zhihu/pkg"

	"zhihu/zhihuRpc/internal/svc"
	"zhihu/zhihuRpc/zhihuRpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type PwdBackLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewPwdBackLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PwdBackLogic {
	return &PwdBackLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *PwdBackLogic) PwdBack(in *zhihuRpc.PwdBackRequest) (*zhihuRpc.PwdBackResponse, error) {
	// todo: add your logic here and delete this line

	user := mysql.User{}
	mysql.DB.Where("tel=?", in.Tel).Find(&user)

	if user.ID == 0 {
		return nil, fmt.Errorf("当前帐号未注册无发找回密码！")
	}

	result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Tel).Result()
	if result != in.SmsCode {
		return nil, fmt.Errorf("短信验证码错误！")
	}

	if in.NewPwd != in.SurePwd {
		return nil, fmt.Errorf("两次密码不一致")
	}

	if in.NewPwd == user.Password {
		return nil, fmt.Errorf("新密码不能与原密码一致")
	}

	user.Password = pkg.Md5(in.NewPwd)
	mysql.DB.Updates(&user)

	return &zhihuRpc.PwdBackResponse{
		UserId: int64(user.ID),
	}, nil
}
